<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" v-loading="formLoading">
      <el-form-item label="选择专业" prop="majorId">
        <!-- 学校 -->
        <el-select v-model="schoolId" placeholder="请选择学校" @change="changeSchool" style="width: 180px;">
          <el-option v-for="item in schools" :key="item.id" :label="item.schoolName" :value="item.id" />
        </el-select>
        <!-- 专业 -->
        <el-select v-model="formData.majorId" placeholder="请选择专业" style="width: 180px;" clearable>
          <el-option v-if="formData.majorId == -1" :key="-1" :label="'无专业数据'" :value="-1" disabled />
          <el-option v-for="item in majors" :key="item.id" :label="item.majorName" :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="班级名称" prop="classinfoName">
        <el-input v-model="formData.classinfoName" placeholder="请输入班级名称" />
      </el-form-item>

    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { ClassinfoApi, ClassinfoVO } from '@/api/td/classinfo'
import { SchoolApi, SchoolForSelectVO } from '@/api/td/school'
import { MajorApi, MajorForSelectVO } from '@/api/td/major'
import { useSystemStore } from '@/store/modules/system'
/** 班级 表单 */
defineOptions({ name: 'ClassinfoForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  majorId: undefined as number | undefined,
  classinfoName: undefined,
})
const formRules = reactive({
  majorId: [{ required: true, message: '专业名称不能为空', trigger: 'blur' }],
  classinfoName: [{ required: true, message: '班级名称不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref
const systemStore = useSystemStore()//系统状态库的实例
const schoolId = ref(undefined)//学校的id
const schools = ref<SchoolForSelectVO[]>([])//获取学校的下拉列表的数据
const majors = ref<MajorForSelectVO[]>([])//获取专业的下拉列表的数据
const getSchoolsForSelect = async () => {
  const data = await SchoolApi.getSchoolsForSelect();
  schools.value = data
}
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  getSchoolsForSelect()
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const response = await ClassinfoApi.getClassinfo(id)
      formData.value = response
      // 从专业ID反查学校ID
      if (formData.value.majorId) {
        const school = await findSchoolByMajorId(formData.value.majorId)
        if (school) {
          schoolId.value = school.id
          await getMajorForSelect(school.id)
        }
      }
    } finally {
      formLoading.value = false
    }
  }
}
// 新增方法：通过专业ID查找所属学校
const findSchoolByMajorId = async (majorId: number) => {
  const schools = await SchoolApi.getSchoolsForSelect()
  for (const school of schools) {
    const majors = await MajorApi.getMajorsBySchoolId(school.id)
    if (majors.some(m => m.id === majorId)) {
      return school
    }
  }
  return null
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
const changeSchool = async (selectedSchooltId: number) => {
  // 清空当前专业选择
  formData.value.majorId = undefined
  majors.value = [];
  // 获取并更新专业列表
  await getMajorForSelect(selectedSchooltId)
  // 只有当选择的学校未变化时才处理
  if (selectedSchooltId !== schoolId.value) return
  // 根据专业数据情况设置专业ID
  formData.value.majorId = majors.value.length > 0 ? majors.value[0].id : -1
}

//通过部门去获取专业
const getMajorForSelect = async (schoolId: number) => {
  const data = await MajorApi.getMajorsBySchoolId(schoolId);
  majors.value = data
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ClassinfoVO
    if (formType.value === 'create') {
      await ClassinfoApi.createClassinfo(data)
      message.success(t('common.createSuccess'))
    } else {
      await ClassinfoApi.updateClassinfo(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    //  触发 store 版本更新
    await systemStore.refresh()
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    majorId: undefined,
    classinfoName: undefined,
  }
  schoolId.value = undefined // 新增：清空学校选择
  formRef.value?.resetFields()
}
</script>
